package com.wanlian.router.net.netty2.handler;


import com.smart.android.utils.Logger;
import com.wanlian.router.net.netty2.msg.MsgType;
import com.wanlian.router.net.netty2.msg.PeerMsg;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * Handles a client-side channel.
 */
public class DeviceClientHandler extends ChannelInboundHandlerAdapter { // (1)
    private final ByteBuf firstMessage;

    public DeviceClientHandler() {
        byte[] req = "Hello from client".getBytes();
        firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {

        Logger.i("DeviceClientHandler >>> channelActive");

        try {
            ctx.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            Logger.i("DeviceClientHandler >>> channelRead");
            PeerMsg peerMsg = (PeerMsg) msg;
            String msgType = peerMsg.getBaseMsg().getType();
            Logger.i("message response " + msgType + ",message=" + peerMsg.getBaseMsg().getContent());

            if (MsgType.REGISTER_SUCCESS.equals(msgType)) {

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        Logger.i("DeviceClientHandler >>> exceptionCaught");

        ctx.close();
    }
}